package jspSamples.unit7.websiteSample;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Function {

    DBConnection DBConn = new DBConnection();


    /**
     * 登录验证
     */
    public boolean CheckLogin(Connection conn, String s1, String s2)
            throws SQLException {
        Statement stmt = conn.createStatement();
        ResultSet rs = null;
        boolean OK = true;
        String AdminPwd = "";
        String User = CheckReplace(s1);
        String Pwd = CheckReplace(s2);
        String Sql = "select * from Admin where AdminName='" + User + "'";
        rs = stmt.executeQuery(Sql);
        if (!rs.next()) {
            OK = false;
        } else {
            AdminPwd = rs.getString("AdminPwd");
            OK = Pwd.equals(AdminPwd);
        }
        return OK;
    }


    /**
     * 字符串过滤
     *
     */
    public String CheckReplace(String s) {

        try{
            if ((s == null) || (s.equals(""))) {
                return "";
            }
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                switch (c) {
                    case '"':
                        stringBuffer.append("&quot;");
                        break;
                    case '\'':
                        stringBuffer.append("&#039");
                        break;
                    case '|':
                        break;
                    case '&':
                        stringBuffer.append("&amp;");
                        break;
                    case '<':
                        stringBuffer.append("&lt;");
                        break;
                    case '>':
                        stringBuffer.append("&gt;");
                        break;
                    default:
                        stringBuffer.append(c);
                }
            }
            return stringBuffer.toString().trim();

        }catch (Exception e) {

        }
        return "";
    }


    /**
     * 日期验证
     * @param s1
     * @param s2
     * @return
     */
    public String checkDate(String[] s1, String[] s2) {
        boolean OK = true;
        StringBuffer sb = new StringBuffer();

        try {
            for (int i = 0; i < s1.length; i++) {
                // 判断字符串是否为空或" "（空格）
                if (s1[i] == null || s1[i].equals("") || s1[i].equals(" ")) {
                    sb.append("<li>[" + s2[i] + "]不能为空！</li>");
                    OK = false;
                }
            }

            if (OK) {
                return "Yes";
            } else {
                return sb.toString().trim();  // 返回错误信息
            }
        } catch (Exception e) {
            return "操作失败！";  // 异常处理
        }
    }


    public String getStrCN(String s) {
        if (s == null) {
            s = "";  // 如果传入的字符串是 null，则将其设置为空字符串
        }

        try {
            byte[] abyte0 = s.getBytes("GBK");  // 将字符串转换为字节数组，使用 GBK 编码
            s = new String(abyte0, "GBK");  // 重新构造字符串
        } catch (Exception e) {
            s = "";  // 如果有异常，返回空字符串
        }

        return s;
    }

    public int strToInt(String str) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {

        }
        return 0;
    }

    public boolean StringToBoolean(String s) {
        return (s != null && s.equals("Yes"));
    }


    public String Page(String sPage, ResultSet rs, int intPage, int intPageSize) {
        String s = "";
        int i = 0;
        try {
            // 获取记录总数
            rs.last();
            int intRowCount = rs.getRow();

            // 计算总页数
            int intPageCount = 0;
            if (intRowCount % intPageSize == 0) {
                intPageCount = intRowCount / intPageSize;
            } else {
                intPageCount = (int) Math.floor(intRowCount / intPageSize) + 1;
            }

            // 防止页码越界
            if (intPageCount == 0) intPageCount = 1;
            if (intPage < 1) intPage = 1;
            if (intPage > intPageCount) intPage = intPageCount;

            // 如果记录数大于页面大小，显示分页控件
            if (intRowCount > intPageSize) {
                s = "<div class=\"container mt-4\">";
                s = s + "<div class=\"row\"><div class=\"col-12\">";

                // 分页信息
                s = s + "<div class=\"alert alert-info\" role=\"alert\">";
                s = s + "当前第" + intPage + "页 / 共 " + intPageCount + "页,&nbsp;&nbsp;&nbsp;&nbsp;共 " + intRowCount + " 条记录,&nbsp;&nbsp;&nbsp;&nbsp;" + intPageSize + " 条/页";
                s = s + "</div>";

                // 分页链接
                s = s + "<nav><ul class=\"pagination justify-content-center\">";

                // 前一页
                if (intPage > 1) {
                    s = s + "<li class=\"page-item\"><a class=\"page-link\" href=\"" + sPage + "intPage=" + (intPage - 1) + "\">上一页</a></li>";
                } else {
                    s = s + "<li class=\"page-item disabled\"><span class=\"page-link\">上一页</span></li>";
                }

                // 页码链接
                int showPage = intPageCount;
                if (showPage > 10) showPage = 10;

                for (i = 1; i <= showPage; i++) {
                    String activeClass = (i == intPage) ? " active" : "";
                    s = s + "<li class=\"page-item" + activeClass + "\"><a class=\"page-link\" href=\"" + sPage + "intPage=" + i + "\">" + i + "</a></li>";
                }

                // 下一页
                if (intPage < intPageCount) {
                    s = s + "<li class=\"page-item\"><a class=\"page-link\" href=\"" + sPage + "intPage=" + (intPage + 1) + "\">下一页</a></li>";
                } else {
                    s = s + "<li class=\"page-item disabled\"><span class=\"page-link\">下一页</span></li>";
                }

                s = s + "</ul></nav>";

                // 页码选择下拉框
                s = s + "<div class=\"form-group\">";
                s = s + "<label for=\"ipage\">跳转到页：</label>";
                s = s + "<select id=\"ipage\" name=\"ipage\" class=\"form-control\" onChange=\"jumpMenu('self',this,0)\">";
                s = s + "<option value=\"\" selected>请选择</option>";

                for (i = 1; i <= intPageCount; i++) {
                    String sSelect = (i == intPage) ? "SELECTED" : "";
                    s = s + "<option value=\"" + sPage + "intPage=" + i + "\"" + sSelect + ">第" + i + "页</option>";
                }

                s = s + "</select>";
                s = s + "</div>";

                s = s + "</div></div></div>";
            }
            return s;
        } catch (Exception e) {
            return "分页出错！";
        }
    }

    public String PageFront(String sPage, ResultSet rs, int intPage, int intPageSize) {
        String s = null;
        int i = 0;
        try {
            // 获取记录总数
            rs.last();
            int intRowCount = rs.getRow();

            // 计算总页数
            int intPageCount = 0;
            if (intRowCount % intPageSize == 0) {
                intPageCount = intRowCount / intPageSize;
            } else {
                intPageCount = (int) Math.floor(intRowCount / intPageSize) + 1;
            }

            if (intPageCount == 0) intPageCount = 1;
            if (intPage < 1) intPage = 1;
            if (intPage > intPageCount) intPage = intPageCount;

            if (intRowCount > intPageSize) {
                s = "<table width=\"90%\" border=\"0\" align=\"left\" cellpadding=\"2\" cellspacing=\"0\"><tr>";

                s = s + "<td style=\"text-align:left\" width=\"80%\" height=\"30\" class=\"chinese\"><span class=\"chinese\">";
                s = s + "当前第" + intPage + "页/共" + intPageCount + "页,&nbsp;&nbsp;&nbsp;&nbsp;共" + intRowCount + "条记录,&nbsp;&nbsp;&nbsp;&nbsp;" + intPageSize + "条/页&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";

                int showPage = intPageCount;
                if (showPage > 10) showPage = 10;

                for (i = 1; i <= showPage; i++) {
                    if (i == intPage) {
                        s = s + "<span>" + i + "</span>";
                    } else {
                        // 其他页，生成链接
                        s = s + "&nbsp;<a style=\"color:#3F862E\" href=\"" + sPage + "intPage=" + i + "\">" + i + "</a>";
                    }
                }

                s = s + "</span></td></tr></table>";
            }

            return s;
        } catch (Exception e) {
            return "分页出错!";
        }
    }
    public boolean AddLog(String[] s) {
        Connection conn = null;
        Statement stmt = null;
        try {
            // 获取数据库连接
            conn = this.DBConn.getConn();
            stmt = conn.createStatement();

            for (int i = 0; i < s.length; i++) {
                s[i] = getStrCN(CheckReplace(s[i]));
            }

            String sql = "INSERT INTO Log(User, LogType, LogTime, IP, Result) VALUES (";
            sql = sql + "'" + s[0] + "', "; // User
            sql = sql + "'" + s[1] + "', "; // LogType
            sql = sql + "'" + s[2] + "', "; // LogTime
            sql = sql + "'" + s[3] + "', "; // IP
            sql = sql + "'" + s[4] + "');"; // Result

            stmt.executeUpdate(sql);

            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            // 关闭数据库连接
            try {
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public String outError(String s) {
        try {
            StringBuffer sb = new StringBuffer();
            sb.append("<tr class=\"chinese\" height=\"25\"><td height=\"27\" background=\"images/bg.gif\" class=\"info\">\r\n");
            sb.append("<div align=\"center\" class=\"title\">错误页面</div></td></tr>\r\n");
            sb.append("<tr class=\"chinese\" height=\"25\"><td><table cellspacing=\"4\" cellpadding=\"1\">\r\n");
            sb.append("<tr><td width=\"511\" height=\"80\" align=\"middle\" valign=\"top\">\r\n");
            sb.append("<p align=\"left\"><span class=\"info1\">操作出错:</span></p>\r\n");
            sb.append("<div align=\"left\" class=\"info1\">" + s + "</div></td></tr></table></td></tr>\r\n");
            sb.append("<tr><td background=\"images/bg.gif\" height=\"20\" valign=\"middle\">\r\n");
            sb.append("<div align=\"center\" class=\"chinese\">\r\n");
            sb.append("<a href=\"#\" onClick=\"javascript:history.go(-1)\">返回</a></div></td></tr>\r\n");
            sb.append("</table></td></tr></table><br><br>\r\n");
            return sb.toString();
        } catch (Exception e) {
            return "操作出错!";
        }
    }

    public String outWarn(String s) {
        try {
            StringBuffer sb = new StringBuffer();
            sb.append("<br><br><form name=\"form1\" method=\"post\" action=\"\">\r\n");
            sb.append("<table border=\"1\" align=\"center\" cellpadding=\"1\" cellspacing=\"2\">\r\n");
            sb.append("<tr><td width=\"400\" height=\"80\" align=\"center\" valign=\"top\">\r\n");
            sb.append("<tr class=\"chinese\" height=\"25\"><td height=\"27\" background=\"images/bg.gif\" class=\"info\">\r\n");
            sb.append("<div align=\"left\" class=\"info1\">系统警告:<br><br>\r\n");
            sb.append("&nbsp;&nbsp;&nbsp;&nbsp;" + s + "</div></td></tr>\r\n");
            sb.append("<tr><td height=\"20\" align=\"center\" valign=\"top\"><div align=\"center\">\r\n");
            sb.append("<input name=\"Submit\" type=\"button\" class=\"button\" value=\"取消\" onClick=\"javascript:history.go(-1);\">&nbsp;&nbsp;\r\n");
            sb.append("<input name=\"OK\" type=\"hidden\" id=\"OK\" value=\"Yes\">\r\n");
            sb.append("<input name=\"Submit2\" type=\"submit\" class=\"button\" value=\"确定\">\r\n");
            sb.append("</div></td>\r\n");
            sb.append("</tr></table></form>\r\n");
            return sb.toString();
        } catch (Exception e) {
            return "操作出错!";
        }
    }

    //获取新闻列表
    public StringBuffer ListNews(StringBuffer sb, ResultSet rs, String strPage, String sPage) throws SQLException {
        int i;
        int intPage = 1;
        int intPageSize = 5;

        // 如果没有记录，显示"没有记录"信息
        if (!rs.next()) {
            sb.append("<tr height=\"25\" class=\"text-center bg-light\"><td colspan=\"5\">\r\n");
            sb.append("<div><b>没有记录</b></div></td></tr>\r\n");
        } else {
            // 获取当前页数
            intPage = strToInt(sPage);
            sPage = CheckReplace(strPage);

            // 如果页数为0，默认设置为1
            if (intPage == 0) intPage = 1;

            // 设置查询游标到当前页
            rs.absolute((intPage - 1) * intPageSize + 1);
            i = 0;

            // 循环遍历当前页的数据
            while (i < intPageSize && !rs.isAfterLast()) {
                int NewsID = rs.getInt("NewsID");
                String NewsTitle = rs.getString("NewsTitle");
                String NewsContent = rs.getString("NewsContent");
                String NewsTime = rs.getString("NewsTime");
                String AdminName = rs.getString("AdminName");

                // 构造新闻条目的表格行，使用 Bootstrap 样式
                sb.append("<tr>");
                sb.append("<td class=\"text-center\">" + NewsID + "</td>");
                sb.append("<td class=\"text-center\">" + NewsTitle + "</td>");
                sb.append("<td class=\"text-center\">" + AdminName + "</td>");
                sb.append("<td class=\"text-center\">" + NewsTime + "</td>");
                sb.append("<td class=\"text-center\">");

                // 操作按钮 - 修改和删除
                sb.append("<div class=\"btn-group\" role=\"group\" aria-label=\"Basic example\">");
                sb.append("<button type=\"button\" class=\"btn btn-primary btn-sm\" data-toggle=\"modal\" data-target=\"#edit-popup\" onclick=\"setEditNews('" + NewsID + "', '" + NewsTitle + "', '" + NewsContent + "')\">修改</button>");
                sb.append("<button type=\"button\" class=\"btn btn-warning btn-sm\" data-toggle=\"modal\" data-target=\"#delete-popup\" onclick=\"setDeleteNewsId('" + NewsID + "')\">删除</button>");
                sb.append("</div>");

                sb.append("</td>");
                sb.append("</tr>");
                rs.next();  // 移动到下一条记录
                i++;
            }

            // 分页
            sb.append(Page(sPage, rs, intPage, intPageSize));
        }
        return sb;
    }



    //添加新闻
    public String AddNews(Connection Conn, Statement stmt, ResultSet rs, String[] s) throws SQLException {
        int z = 0;
        int newNum = 0;

        try {
            if (!rs.next()) {
                newNum = 1;
            } else {
                while (z < 1 && !rs.isAfterLast()) {
                    int NewsID = rs.getInt("NewsID");
                    newNum = NewsID + 1;
                    z++;
                }
            }

            for (int i = 0; i < s.length; i++) {
                if (i != 1) {
                    s[i] = getStrCN(CheckReplace(s[i]));
                } else {
                    s[i] = getStrCN(s[i]);
                }
            }

            // 获取当前时间
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String newsTime = format.format(new Date());

            // 构建 SQL 插入语句
            StringBuilder sql = new StringBuilder();
            sql.append("INSERT INTO News (NewsID, NewsTitle, NewsContent, NewsTime, AdminName) ");
            sql.append("VALUES (");
            sql.append(newNum).append(", ");
            sql.append("'").append(s[0]).append("', ");
            sql.append("'").append(s[1]).append("', ");
            sql.append("'").append(newsTime).append("', ");
            sql.append("'mr')");

            // 执行数据库操作
            Conn.setAutoCommit(false);
            stmt.executeUpdate(sql.toString());
            Conn.commit();
            Conn.setAutoCommit(true);

            stmt.close();
            Conn.close();

            return "Yes";  // 操作成功

        } catch (Exception e) {
         Conn.rollback();
         e.printStackTrace();
         Conn.close();
         return "添加失败！";
        }
    }

    //删除新闻

    public boolean DelNews(Connection Conn, Statement stmt, int NewsID) throws SQLException {
        if (NewsID == 0) {
            return false;  // 如果传入的 NewsID 为 0，返回 false 表示失败
        }

        try {
            String sql = "DELETE FROM News WHERE NewsID = " + NewsID;
            Conn.setAutoCommit(false);
            stmt.executeUpdate(sql);
            Conn.commit();
            Conn.setAutoCommit(true);
            stmt.close();
            Conn.close();
            return true;  // 删除成功，返回 true

        } catch (SQLException e) {
            Conn.rollback();
            e.printStackTrace();
            Conn.close();
            return false;
        }
    }

    //x修改新闻
    public String EditNews(Connection Conn, Statement stmt, String[] s, String newsId) throws SQLException {
        if (s == null || s.length < 2 || newsId == null || newsId.isEmpty()) {
            return "输入参数无效！";
        }

        for (int i = 0; i < s.length; i++) {
            s[i] = getStrCN(CheckReplace(s[i]));
        }
        int NewsID = strToInt(newsId);

        StringBuffer sql = new StringBuffer();
        sql.append("UPDATE News SET ");
        sql.append("NewsTitle = '" + s[0] + "', ");
        sql.append("NewsContent = '" + s[1] + "' ");
        sql.append("WHERE NewsID = " + NewsID);
        try {
            stmt.executeUpdate(sql.toString());
            stmt.close();
            Conn.close();

            return "Yes";

        } catch (SQLException e) {
            e.printStackTrace();
            try {
                if (stmt != null) stmt.close();
                if (Conn != null) Conn.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            return "操作失败！";
        }
    }

    //获取新闻信息列表（前台）
    public StringBuffer ListNewsFront(StringBuffer sb, ResultSet rs, String toPage, String pageNum) throws SQLException {
        int i;
        int intPage = 1;
        int intPageSize = 5;

        if (!rs.next()) {
            sb.append("<tr height=\"25\" bgcolor=\"#d6dff7\" class=\"info1\"><td colspan=\"5\">\r\n");
            sb.append("<div align=\"center\"><b>没有记录!</b></div></td></tr>\r\n");
        } else {
            intPage = strToInt(pageNum);
            toPage = CheckReplace(toPage);
            if (intPage == 0) intPage = 1;
            rs.absolute((intPage - 1) * intPageSize + 1);
            i = 0;

            while (i < intPageSize && !rs.isAfterLast()) {
                int NewsID = rs.getInt("NewsID");
                String NewsTitle = rs.getString("NewsTitle");
                String NewsTime = rs.getString("NewsTime");
                String AdminName = rs.getString("AdminName");

                sb.append("<tr>");
                sb.append("<td>" + NewsTitle + "</td>");
                sb.append("<td style=\"text-align:center\">" + AdminName + "</td>");
                sb.append("<td style=\"text-align:center\">" + NewsTime + "</td>");
                sb.append("<td style=\"text-align:center\"><a style=\"color:#3F862E\" target=\"_blank\" href=\"newsFrontDetail.jsp?newsId=" + NewsID + "\">详情</a></td>");
                sb.append("</tr>");

                rs.next();
                i++;
            }

            sb.append(PageFront(toPage, rs, intPage, intPageSize));
        }

        return sb;
    }

//获取每条新闻详细信息(前台)
public StringBuffer FrontNewsDetail(StringBuffer sb, ResultSet rs) throws SQLException {
    int i = 0;
    while (i < 1 && !rs.isAfterLast()) {
        rs.next();
        String NewsTitle = rs.getString("NewsTitle");
        String NewsContent = rs.getString("NewsContent");
        String[] content = NewsContent.split("#");

        sb.append("<br><h2 style=\"font-size:28px;margin-left:30px\">" + NewsTitle + "</h2>");
        for (int j = 0; j < content.length; j++) {
            sb.append("<p>" + content[j] + "</p>");
        }

        i++;
    }
    return sb;
}



}